//抓取get数据
const http = require('http');
const qs= require('querystring');
const url = require('url');
const fs = require('fs');

let users={};

let server = http.createServer((req,res)=>{
  let {pathname,query} = url.parse(req.url,true);
  let str='',postData;//这么干会有点问题
  //有一段数据到达了 触发的事件
  req.on('data',data=>{str+=data;});
  //所有数据接口完成 事件
  req.on('end',()=>{
    postData = qs.parse(str);
    //在这儿写逻辑，
    switch (pathname) {
      //get方法
      case '/reg':
        let {username,password} = query;
        if(!username){
          res.write(`{'code':-1,'msg':'username is requery'}`);
        }else if(!password){
          res.write(`{'code':-1,'msg':'password is requery'}`);
        }else if(users[username]){
          res.write(`{'code':-1,'msg':'user is exist'}`);
        }else{
          users[username] = password;
          res.write(`{'code':0,'msg':'success'}`);
        }
        res.end();
        break;
      //post方法
      case '/login':
        if(!postData.username){
          res.write(`{'code':-1,'msg':'username is requery'}`);
        }else if(!postData.password){
          res.write(`{'code':-1,'msg':'password is requery'}`);
        }else if(users[postData.username]==postData.password){
          res.write(`{'code':0,'msg':'login success'}`);
        }else if(users[postData.username]!=postData.password){
          res.write(`{'code':-1,'msg':'user or password is wrong'}`);
        }
        res.end();
        break;
      default:
        fs.readFile(`www${pathname}`,(err,data)=>{
          if(err){
            res.writeHead(404);
            res.write('Not Found');
          }
          else res.write(data);
          res.end();
        });
    }
    console.log(pathname,query,postData);
  });
});

server.listen(8080);
